package com.orange.controller.news;

import com.orange.bean.core.constant.CacheConstants;
import com.orange.bean.rebangTody.dto.request.HotNewsReq;
import com.orange.bean.rebangTody.dto.response.HotNewsRes;
import com.orange.bean.rebangTody.vo.NewsListRes;
import com.orange.bean.todayNews.dto.response.WordCloudRes;
import com.orange.common.annotation.PassToken;
import com.orange.common.base.controller.impl.BaseControllerImpl;
import com.orange.common.utils.StringUtil;
import com.orange.framework.result.R;
import com.orange.project.news.service.NewsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2025/8/11 15:08
 */
@RestController
@RequestMapping("/news/")
public class NewsController extends BaseControllerImpl {

    protected final static Logger logger = LoggerFactory.getLogger(NewsController.class);

    @Autowired
    private NewsService newsService;

    @GetMapping(value = "getNewsListForNet")
    @PassToken
    public R<HotNewsRes.News> getNewsListForPage() {
        HotNewsReq hotNewsReq = HotNewsReq.builder().page("1").tab("top").subTab("today").version("1").build();
        HotNewsRes newsRes = newsService.getNewsListForNet(hotNewsReq);
        List<HotNewsRes.News> newsListRes = newsRes.getList();
        List<HotNewsRes.News> collect = newsListRes.stream()
                .peek(news -> news.setTypeN(CacheConstants.NEWS_TYPE.get(news.getType())))
                .collect(Collectors.toList());
        return R.ok().data(collect);
    }

    @RequestMapping(value = "initRemoteNewsToCache", method = RequestMethod.GET)
    @PassToken
    @Scheduled(cron = "0 0 */6 * * ?")
    public R initRemoteNewsToCache() {
        List<HotNewsRes.News> newsAllList = new ArrayList<>();
        int currentPage = 1;
        int totalPage = 1; // 初始设为最大值
        while (currentPage <= totalPage) {
            HotNewsReq hotNewsReq = HotNewsReq.builder().page(String.valueOf(currentPage)).tab("top").subTab("today").version("1").build();
            HotNewsRes newsRes = newsService.getNewsListForNet(hotNewsReq);

            if (newsRes == null) {
                logger.error("获取第{}页新闻数据失败", currentPage);
                break;
            }
            List<HotNewsRes.News> newsResList = newsRes.getList();
            if (newsResList != null) {
                newsAllList.addAll(newsResList);
            }
            totalPage = newsRes.getTotalPage(); // 更新总页数
            currentPage++; // 准备获取下一页
        }

        //logger.info("最终查询新闻列表：{}", newsAllList);

        long cacheSize = redisCache.lGetListSize(CacheConstants.HOT_NEWS_LIST);
        if (cacheSize > 0) {
            redisCache.delete(CacheConstants.HOT_NEWS_LIST);
        }
        redisCache.lSet(CacheConstants.HOT_NEWS_LIST, newsAllList);
        logger.info("共获取{}条新闻数据", newsAllList.size());
        return R.ok().message("共获取" + newsAllList.size() + "条新闻数据");
    }

    /**
     * 新闻列表查询所有列表（缓存）
     *
     * @return
     */
    @GetMapping(value = "getNewsListForCache")
    @PassToken
    public R getNewsList() {
        List<NewsListRes> newsRes = newsService.getCacheNewsList();
        return R.ok().data(newsRes);
    }

    /**
     * 新闻列表查询分页查询（缓存）
     *
     * @return
     */
    @GetMapping(value = "getNewsListForPage")
    @PassToken
    public R getNewsListForPage(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        List<NewsListRes> newsRes = newsService.getCacheNewsPageList(pageNum, pageSize);
        return R.ok().data(newsRes);
    }




    @GetMapping(value = "v2/getNewsListForNet")
    @PassToken
    public R getNowNewsList(@RequestParam("id") String id) {
        List<NewsListRes> newsRes = newsService.getNowNewsList(id);
        return R.ok().data(newsRes);
    }


    @GetMapping(value = "v2/getNewsListForPage")
    @PassToken
    public R getNewsListForCache(String type,
                                 @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        List<NewsListRes> newsRes = newsService.getCacheNowNewsList(StringUtil.isEmpty(type) ? "all" : type, pageNum, pageSize);
        return R.ok().data(newsRes);
    }

    @GetMapping(value = "v2/initNowNewsToCache")
    @Scheduled(cron = "0 0 */1 * * ?")
    @PassToken
    public R initNowNewsToCache() {
        newsService.initNowNewsToCache();
        return R.ok();
    }

    @GetMapping(value = "getHotWordCloudForCache")
    @PassToken
    public R getHotWordCloudForCache() {
        List<WordCloudRes> hotWordCloud = newsService.getHotWordCloudForCache();
        return R.ok().data(hotWordCloud);
    }

    @GetMapping(value = "v2/getHotWordCloudForCache")
    @PassToken
    public R getHotWordCloudForCacheV2() {
        List<WordCloudRes> hotWordCloud = newsService.getHotWordCloudForCacheV2();
        return R.ok().data(hotWordCloud);
    }

}
